package com.lyh.hkcloud.base;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.text.Html;
import android.view.*;
import android.webkit.WebView;
import android.widget.*;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import cn.yhq.validate.ValidateManager;
import com.lyh.hkcloud.R;
import com.lyh.hkcloud.activity.*;
import com.lyh.hkcloud.constants.*;
import com.lyh.hkcloud.util.base.*;
import com.lyh.hkcloud.util.http.Request;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public abstract class BaseActivity extends AppCompatActivity {

    private ValidateManager validateManager = new ValidateManager();

    protected ViewGroup rootView;

    protected Button btnClear;

    protected Button btnSubmit;

    protected Boolean enableSubmitConfirm = false;

    protected String submitConfirmMsg;

    protected Map<Integer, Object> initValues = new HashMap<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(getLayoutResId());
        init();
        LogUtil.i("activity", this.getClass().getName());
    }

    @Override
    public final void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
    }

    protected void init() {
        onBeginInit();
        initDefaultView();
        initView();
        saveInitValue(rootView);
        initDefaultEvent();
        initEvent();
        initData();
        onAfterInit();
        initValidateManager(validateManager);
    }

    protected abstract Activity getActivity();

    protected abstract int getLayoutResId();

    protected int getClearResId() {
        return -1;
    }

    protected int getSubmitResId() {
        return -1;
    }

    protected void saveInitValue(ViewGroup vg) {
        int count = vg.getChildCount();
        for (int i = 0; i < count; i++) {
            View view = vg.getChildAt(i);
            if (view instanceof WebView) {
                return;
            }
            if (view.getId() != -1) {
                if (view instanceof CheckBox) {
                    initValues.put(view.getId(), ((CheckBox) view).isChecked());
                } else if (view instanceof TextView) {
                    initValues.put(view.getId(), ((TextView) view).getText().toString());
                }
            }
            if (view instanceof ViewGroup) {
                saveInitValue((ViewGroup) view);
            }
        }
    }


    protected void onBeginInit() {
    }

    protected void onAfterInit() {
    }

    protected abstract void initView();

    protected void initEvent() {
    }

    protected void initData() {
    }

    private void initDefaultView() {
        rootView = findViewById(android.R.id.content);
        btnClear = findViewById(getClearResId());
        btnSubmit = findViewById(getSubmitResId());
    }

    private AlertDialog submitAlertDialog;

    private void initDefaultEvent() {
        if (btnClear != null) {
            btnClear.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onClear();
                }
            });
        }

        if (btnSubmit != null) {
            btnSubmit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (StringUtils.isEmpty(submitConfirmMsg)) {
                        submitConfirmMsg = "确定" + ((TextView) v).getText().toString().replaceAll(" ", "").replaceAll(" ", "") + "吗？";
                    }
                    submit();
                }
            });
        }
    }

    protected void submit() {
        if (validateManager.validate() && onValidate()) {
            if (enableSubmitConfirm && StringUtils.isNotEmpty(submitConfirmMsg)) {
                if (submitAlertDialog != null && submitAlertDialog.isShowing()) {
                    ToastUtils.makeText(getActivity(), "请勿重复提交！", ToastUtils.LENGTH_SHORT).show();
                    return;
                }

                submitAlertDialog = new AlertDialog.Builder(getActivity()).setTitle("提示").
                        setIcon(R.drawable.submit).
                        setMessage(Html.fromHtml(submitConfirmMsg)).
                        setPositiveButton("确定", new DialogInterface.OnClickListener() {// 设置确定按钮
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                onSubmit();
                            }
                        }).setNegativeButton("取消", null).setCancelable(false).create();
                submitAlertDialog.show();
            } else {
                onSubmit();
            }
        }
    }

    protected void reset(ViewGroup vg) {
        reset(vg, new HashSet<Integer>());
    }

    protected void reset(ViewGroup vg, Set<Integer> ignoreSet) {

        int count = vg.getChildCount();
        for (int i = 0; i < count; i++) {
            View view = vg.getChildAt(i);
            if (view instanceof WebView) {
                return;
            }
            if (view.getId() != -1 && !ignoreSet.contains(view.getId())) {
                if (view instanceof CheckBox) {
                    ((CheckBox) view).setChecked(StringUtils.toBoolean(initValues.get(view.getId()), false));
                } else if (view instanceof TextView) {
                    ((TextView) view).setText(StringUtils.toString(initValues.get(view.getId()), ""));
                }
            }
            if (view instanceof ViewGroup && !(view instanceof Spinner)) {
                reset((ViewGroup) view, ignoreSet);
            }
        }
    }

    protected void alert(String msg) {
        alert("提示", msg);
    }

    protected void alert(String title, String msg) {
        new AlertDialog.Builder(getActivity())
                .setIcon(R.drawable.alert)
                .setTitle(title)
                .setMessage(msg)
                .setPositiveButton("确定", null)
                .create().show();
    }

    protected void confirm(String title, String msg, final ConfirmListener listener) {
        new androidx.appcompat.app.AlertDialog.Builder(getActivity()).setTitle(title).setMessage(msg).setIcon(R.drawable.ask)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        listener.success();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                listener.cancel();
            }
        }).create().show();
    }

    /**
     * 提交按钮事件
     */
    protected void onSubmit() {
    }

    /**
     * 除了默认清楚的内容外，额外的扩展清理，请调用此方法，
     */
    protected void onClear(View... ignores) {
        Set<Integer> vsSet = new HashSet<>();
        if (ignores != null) {
            for (View v : ignores) {
                if (v != null) {
                    vsSet.add(v.getId());
                }
            }
        }
        reset(rootView, vsSet);
    }

    protected void showInfo() {
        new AlertDialog.Builder(this)
                //.setTitle("个人信息")
                .setMessage(StringUtils.toString(UserInfo.networkName, "") + "\n\n用户ID：" + StringUtils.toString(UserInfo.userId, "")
                        + "\n\n用户工号：" + StringUtils.toString(UserInfo.psnCode, "")
                        + "\n\n用户姓名：" + StringUtils.toString(UserInfo.psnName, "")
                        + "\n\n所属部门：" + StringUtils.toString(UserInfo.userGrpName, ""))
                //.setPositiveButton("OK", null)
                .create().show();
    }

    protected void logout() {
        //userService.logout();
        SaveData.putValue(getApplicationContext(), "account", null);
        SaveData.putValue(getApplicationContext(), "password", null);
        SaveData.putValue(getApplicationContext(), "keyId", null);
        UserInfo.keyId = null;
        UserInfo.userId = null;
        this.startActivity(new Intent(getActivity(), LoginActivity.class));
        this.finish();
    }

    protected boolean onValidate() {
        return true;
    }

    protected void initValidateManager(ValidateManager validateManager) {
    }


    public void setEnableSubmitConfirm(Boolean enableSubmitConfirm) {
        this.enableSubmitConfirm = enableSubmitConfirm;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        LoadingUtils.reset();
        super.onDestroy();
    }

    public abstract static class ConfirmListener {
        protected abstract void success();

        protected void cancel() {
        }
    }
}
